package du.myseckill.controller;

import du.myseckill.dto.Login;
import du.myseckill.dto.Register;
import du.myseckill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/{userName}/{password}/login",method = RequestMethod.POST,
            produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public Login login(@PathVariable("userName") String userName, @PathVariable("password") String password, HttpServletRequest request, HttpServletResponse response){
        Login login = userService.login(userName, password);
        if(login.isLogin()){
            HttpSession session = request.getSession(true);
            session.setAttribute("userId",login.getUserId());
            session.setAttribute("userName",userName);
            session.setAttribute("userPhone",login.getPhone());
        }
        return login;
    }

    @RequestMapping(value = "/{userName}/{password}/{userPhone}/register",method = RequestMethod.POST,
            produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public Register register(@PathVariable("userName") String userName, @PathVariable("userPhone") long userPhone, @PathVariable("password") String password){
        Register register=userService.register(userName,password,userPhone);
        return register;
    }


    @RequestMapping("/login")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response){
        request.getSession().removeAttribute("userName");
        request.getSession().removeAttribute("userPhone");
        request.getSession().removeAttribute("userId");
        Cookie userPhone = new Cookie("userPhone", null);
        userPhone.setPath("/secKill");
        response.addCookie(userPhone);
        return "redirect:/secKill/goodsList";
    }

    @RequestMapping("/register")
    public String register(){
        return "register";
    }
}
